import socket
import threading
from src.config_reader import get_port
from src.data_handler import handle_command
from src.logger import setup_logging

logger = setup_logging()


def handle_client(client_socket, client_address):
    try:
        data = client_socket.recv(1024).decode()
        if data:
            response = handle_command(data)
            client_socket.send(response.encode())
    except Exception as e:
        logger.error(f"Error handling client {client_address}: {e}")
    finally:
        client_socket.close()


def main():
    port = get_port()
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('localhost', port)
    server_socket.bind(server_address)
    server_socket.listen(5)
    logger.info(f"Server is listening on port {port}")

    while True:
        client_socket, client_address = server_socket.accept()
        client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
        client_thread.start()


if __name__ == "__main__":
    main()